<template>
  <div class="container">
    <Header>
      <!-- <i slot='left' class="iconfont icon-jiantou1" @click=""></i> -->
      收货地址
    </Header>
    <van-address-list v-model="id" :list="list" @add="onAdd" @edit="onEdit" @select="onselect">
      <div slot="default" class="tip">{{ tip }}</div>
    </van-address-list>
  </div>
</template>
<script>
import Vue from 'vue'
import { AddressList } from 'vant'
import areaList from '@/area/area.js'
import axios from '@/utils/request'
import Header from '@/components/header.vue'
Vue.use(AddressList)
export default {
  data () {
    return {
      id: '',
      list: [],
      tip: ''
    }
  },
  created () {
    let userid = localStorage.getItem('userid')
    axios.get(`/users/address?userid=${userid}`).then(res => {
      if (res.data.code !== '200') {
        this.$router.push('/login')
      } else {
        this.tip = res.data.message
        if (res.data.data) {
          this.list = res.data.data
          new Promise(resolve => {
            this.list.map(item => {
              if (item.isDefault) {
                this.id = item.id
              }
            })
            resolve()
          }).then(() => {
            if (!this.id) {
              this.id = this.list[0].id
            }
          })
        }
      }
    })
  },
  methods: {
    onAdd () {
      this.$router.push('/addsite')
    },
    onEdit (item) {
      this.$router.push('/addsite')
      for (const i in areaList.county_list) {
        if (areaList.county_list[i] === item.province) {
          item.areaCode = i
        }
      }
      localStorage.setItem('edit', JSON.stringify({
        addressid: item.addressid,
        name: item.name,
        tel: item.tel,
        province: item.province,
        city: item.city,
        county: item.county,
        addressDetail: item.addressDetail,
        areaCode: item.areaCode
      }))
    },
    onselect (item, index) {
      localStorage.setItem('address', JSON.stringify({
        address: item.address,
        tel: item.tel,
        name: item.name
      }))
    }
  },
  components: {
    Header
  }
}
</script>
<style lang="scss">
@import '@/lib/reset.scss';
.container {
  header {
    @include flexbox();
    @include justify-content(space-between);
  }
  .van-address-list {
    .tip {
      @include font-size(.2rem);
      @include text-align();
    }
  }
  .van-address-list {
    .tip {
      @include font-size(.2rem);
      @include text-align();
    }
  }
}
</style>
